﻿Imports System.Net
Imports System.IO

Public Class repository

    Public Class cli
        Public Sub New(Optional DefaultDirectory As String = "c:\wpi\apps")
            _DefaultAppDirectory = DefaultDirectory
        End Sub

        Public Sub AddRepo(RepoUrl As String)
            SetConsoleColors(ConsoleColor.aqua)
            Console.WriteLine("Probing repo '" & RepoUrl & "'...")
            SetConsoleColors(ConsoleColor.grey)

            Dim S1 As Boolean = False
            Dim S2 As Boolean = False

            Dim webRequest As WebRequest
            Dim webresponse As WebResponse
            Dim inStream As StreamReader
            Try
                webRequest = webRequest.Create(RepoUrl & "/repo.xml")
                S1 = True
            Catch ex As Exception
                SetConsoleColors(ConsoleColor.red)
                Console.WriteLine(ex.Message)
                SetConsoleColors(ConsoleColor.grey)
                Exit Sub
            End Try

            If S1 Then
                SetConsoleColors(ConsoleColor.aqua)
                Console.WriteLine("Repo config file present.")
                SetConsoleColors(ConsoleColor.grey)
                Try
                    webresponse = webRequest.GetResponse()
                    S2 = True
                Catch ex As WebException
                    SetConsoleColors(ConsoleColor.red)
                    Console.WriteLine(ex.Message)
                    SetConsoleColors(ConsoleColor.grey)
                    Exit Sub
                End Try
            End If
            If S2 Then
                SetConsoleColors(ConsoleColor.aqua)
                Console.WriteLine("Reading config file...")
                SetConsoleColors(ConsoleColor.grey)
                Try
                    inStream = New StreamReader(webresponse.GetResponseStream())
                    While Not inStream.EndOfStream
                        Dim a As String = inStream.ReadLine
                        Select Case True
                            Case a.Trim.ToLower.StartsWith("<name>")
                                Dim DB As New db
                                Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
                                DB.SetData(C, "insert into repo (reponame,repourl,dateadded) values('" & GetXmlElem(a.Trim) & "','" & RepoUrl & "',now())")
                                SetConsoleColors(ConsoleColor.aqua)
                                Console.WriteLine("Repo added.")
                                SetConsoleColors(ConsoleColor.grey)
                        End Select
                    End While
                Catch ex As Exception
                    SetConsoleColors(ConsoleColor.red)
                    Console.WriteLine(ex.Message)
                    SetConsoleColors(ConsoleColor.grey)
                    Exit Sub
                End Try
            End If
        End Sub

        Public Sub RemoveRepo(RepoName As String)
            SetConsoleColors(ConsoleColor.yellow)
            Console.Write("Remove repo '" & RepoName & "'? This will prevent app updates. [Y/N] ")
            SetConsoleColors(ConsoleColor.grey)
            Dim K As String = Console.Read
            SetConsoleColors(ConsoleColor.grey)
            If Chr(K.ToLower) <> "y" Then Exit Sub

            Dim DB As New db
            Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
            Console.WriteLine("Removing packages from '" & RepoName & "'...")
            DB.SetData(C, "delete from pkga where id_repo=(select id from repo where repo.reponame='" & RepoName & "')")
            SetConsoleColors(ConsoleColor.aqua)
            Console.WriteLine("Repo packages removed.")
            SetConsoleColors(ConsoleColor.grey)

            Console.WriteLine("Removing repo '" & RepoName & "'...")
            DB.SetData(C, "delete from repo where reponame='" & RepoName & "'")
            SetConsoleColors(ConsoleColor.aqua)
            Console.WriteLine("Repo removed.")
            SetConsoleColors(ConsoleColor.grey)
        End Sub

        Public Sub UpdateRepos()
            SetConsoleColors(ConsoleColor.aqua)
            Console.WriteLine("Probing repos for avaliable packages...")
            SetConsoleColors(ConsoleColor.grey)

            Dim DB As New db
            Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
            Dim R As OleDb.OleDbDataReader
            R = DB.GetDataReader(C, "select * from repo order by reponame")
            If Not IsNothing(R) Then
                If R.HasRows Then
                    While R.Read
                        Console.WriteLine("Probing " & R("reponame").ToString)
                        Dim S1 As Boolean = False
                        Dim S2 As Boolean = False

                        Dim webRequest As WebRequest
                        Dim webresponse As WebResponse
                        Dim inStream As StreamReader
                        Try
                            webRequest = webRequest.Create(R("repourl").ToString & "/repo.xml")
                            S1 = True
                        Catch ex As Exception
                            SetConsoleColors(ConsoleColor.red)
                            Console.WriteLine(ex.Message)
                            SetConsoleColors(ConsoleColor.grey)
                            Exit Sub
                        End Try

                        If S1 Then
                            SetConsoleColors(ConsoleColor.aqua)
                            Console.WriteLine("Repo config file present.")
                            SetConsoleColors(ConsoleColor.grey)
                            Try
                                webresponse = webRequest.GetResponse()
                                S2 = True
                            Catch ex As WebException
                                SetConsoleColors(ConsoleColor.red)
                                Console.WriteLine(ex.Message)
                                SetConsoleColors(ConsoleColor.grey)
                                Exit Sub
                            End Try
                        End If
                        If S2 Then
                            SetConsoleColors(ConsoleColor.aqua)
                            Console.WriteLine("Reading config file...")
                            SetConsoleColors(ConsoleColor.grey)
                            Try
                                inStream = New StreamReader(webresponse.GetResponseStream())
                                Dim C2 As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
                                SetConsoleColors(ConsoleColor.aqua)
                                Console.WriteLine("Removing packages from repo...")
                                SetConsoleColors(ConsoleColor.grey)
                                DB.SetData(C2, "delete from pkga where id_repo=" & R("id").ToString & "")
                                While Not inStream.EndOfStream
                                    Dim a As String = inStream.ReadLine
                                    Select Case True
                                        Case a.Trim.ToLower.StartsWith("<pckg ")
                                            DB.SetData(C2, "insert into pkga (id_repo,pkgname,pkgmajor,pkgminor,pkg32,pkg64,pkgfile) values(" & R("id").ToString & ",'" & GetXmlElem(a.Trim) & "','" & GetXmlAttrib(a.Trim, "major") & "','" & GetXmlAttrib(a.Trim, "minor") & "'," & GetXmlAttrib(a.Trim, "x32") & "," & GetXmlAttrib(a.Trim, "x64") & ",'" & R("repourl").ToString & "/" & GetXmlAttrib(a.Trim, "file") & "')")
                                            SetConsoleColors(ConsoleColor.aqua)
                                            Console.WriteLine("Package '" & GetXmlElem(a.Trim) & "' added...")
                                            SetConsoleColors(ConsoleColor.grey)
                                    End Select
                                End While
                            Catch ex As Exception
                                SetConsoleColors(ConsoleColor.red)
                                Console.WriteLine(ex.Message)
                                SetConsoleColors(ConsoleColor.grey)
                                Exit Sub
                            End Try
                        End If
                    End While
                Else
                    Console.WriteLine("List empty")
                End If
            Else
                Console.WriteLine("Error fetching list")
            End If
        End Sub

        Public Sub ListRepos()
            SetConsoleColors(ConsoleColor.yellow)
            Console.WriteLine("Repo list:")
            SetConsoleColors(ConsoleColor.grey)
            Dim DB As New db
            Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
            Dim R As OleDb.OleDbDataReader
            R = DB.GetDataReader(C, "select * from repo order by reponame")
            If Not IsNothing(R) Then
                If R.HasRows Then
                    SetConsoleColors(ConsoleColor.white)
                    Console.Write("{0,-20}", "Date added")
                    Console.Write("{0,-25}", "Repo name")
                    Console.WriteLine("Repo URL")
                    SetConsoleColors(ConsoleColor.grey)
                    While R.Read
                        Console.Write("{0,-20}", R("dateadded").ToString)
                        Console.Write("{0,-25}", R("reponame").ToString)
                        Console.WriteLine(R("repourl").ToString)
                    End While
                Else
                    Console.WriteLine("List empty")
                End If
            Else
                Console.WriteLine("Error fetching list")
            End If
        End Sub

    End Class

    Public Class gui

    End Class

End Class
